package wnhz.com.business;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.base.MyBaseActivity;
import wnhz.com.business.groupshop.bean.InfoBean;
import wnhz.com.business.netcallback.DialogCallback;
import wnhz.com.business.uitls.Base64Util;
import wnhz.com.business.uitls.CountDownTimerUtils;
import wnhz.com.business.uitls.Prefer;
import wnhz.com.business.uitls.StatusBarUtil;
import wnhz.com.business.uitls.Url;

/**
 * Created by lizhenglong on 2017-10-24 0024.
 * 获取注册的验证码
 */

public class RegisterGetCodeActivtity extends MyBaseActivity {
    private static final String TAG = "RegisterGetCodeActivtity";

    @BindView(R.id.v_statusbar)
    View vStatusbar;
    @BindView(R.id.rl_register_back)//返回按钮
            RelativeLayout rl_register_back;
    @BindView(R.id.ed_register_code)//输入验证码
            EditText ed_register_code;
    @BindView(R.id.tv_register_getcode)//获取验证码
            TextView tv_register_getcode;
    @BindView(R.id.ed_register_relaname)//真实姓名
            EditText ed_register_ielaname;
    @BindView(R.id.ed_register_idnum)//身份证号码
            EditText ed_register_idnum;
    @BindView(R.id.btn_register2)//注册按钮
            Button btn_register2;
    @BindView(R.id.tv_register_phone)//电话号码
            TextView tv_register_phone;

    private String phone = "";
    private String pwd = "";
    private String invitationcode = "";//邀请码
    private String ptype = "";//手机号归属
    private CountDownTimer countDownTimer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registergetcode);
        ButterKnife.bind(this);


        //状态栏设置
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.transparent), 0);
        StatusBarUtil.setDarkMode(this, true);
        StatusBarUtil.immersive(this, 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            //透明状态栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
////            //透明导航栏
////            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
////            //改变状态栏颜色
////            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            vStatusbar.setVisibility(View.VISIBLE);
            //获取到状态栏的高度
            int statusHeight = getStatusBarHeight();
            //动态的设置隐藏布局的高度
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) vStatusbar.getLayoutParams();
            params.height = statusHeight;
            vStatusbar.setLayoutParams(params);
        }


        phone = getIntent().getStringExtra("phone");
        pwd = getIntent().getStringExtra("pwd");
        invitationcode = getIntent().getStringExtra("invitationcode");
        ptype = getIntent().getStringExtra("ptype");
        tv_register_phone.setText(phone);

        registerCode();//获取验证码
    }


    @OnClick({R.id.tv_register_getcode, R.id.btn_register2,R.id.rl_register_back})
    void click(View view) {
        switch (view.getId()) {
            case R.id.rl_register_back:
                finish();
                break;
            case R.id.tv_register_getcode://点击获取验证码

                registerCode();
                //获取验证码
                countDownTimer = new CountDownTimer(60000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        tv_register_getcode.setEnabled(false);
                        String txt = millisUntilFinished / 1000 + getResources().getString(R.string.resend);
                        tv_register_getcode.setText(txt);
                    }

                    @Override
                    public void onFinish() {
                        tv_register_getcode.setText(getResources().getString(R.string.login_getcode));
                        tv_register_getcode.setEnabled(true);
                    }
                }.start();

                break;
            case R.id.btn_register2:
                userRegister();
                break;
        }
    }

    private void userRegister() {
        Log.e("注册用户", "" + Url.REGISTER_USER);
        Log.e("code",ed_register_code.getText().toString());
        Log.e("mobile", Base64Util.encodedString2(phone));
        Log.e("password", Base64Util.encodedString2(pwd));
        Log.e("ptype", ptype);
        Log.e("invite", invitationcode);
        Log.e("name", ed_register_ielaname.getText().toString());
        Log.e("idCard", Base64Util.encodedString2(ed_register_idnum.getText().toString()));
        Log.e("reg_tye","1");
        OkGo.<InfoBean>post(Url.REGISTER_USER)
                .tag(this)
                .params("code", ed_register_code.getText().toString())
                .params("mobile", Base64Util.encodedString2(phone))
                .params("password", Base64Util.encodedString2(pwd))
                .params("ptype", ptype)
                .params("invite", invitationcode)
                .params("name", ed_register_ielaname.getText().toString())
                .params("idCard", Base64Util.encodedString2(ed_register_idnum.getText().toString()))
                .params("reg_tye", 1)//1手机注册   2第三方注册
                .execute(new DialogCallback<InfoBean>(this) {
                    @Override
                    public void onSuccess(Response<InfoBean> response) {
                        Log.e("REGISTER_GETCODE", "" + response.body());
                        if (response.body().getRe().equals("1")) {
                            handler.sendEmptyMessage(101);
                            MyToast(response.body().getInfo());
                            Prefer.getInstance().setPhone(phone);
                            MyApplication.setToken(response.body().getToken());
                            Intent intent = new Intent(RegisterGetCodeActivtity.this,CompleteInfoActivity.class);
                            intent.putExtra("completetype","1");//从注册界面进入
                            startActivity(intent);
                        } else {
                            MyToast(response.body().getInfo());
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                    @Override
                    public void onError(Response<InfoBean> response) {
                        super.onError(response);
                    }
                });
    }


    //    获取验证码
    //    @param Str    code      接口请求密码  UNOHACHA
    //    @param Int    mobile    手机号   （加密）
    //    @param Int    type      1 注册  2 登录  3 忘记密码   4 更换手机号  5 修改交易密码  6 修改登录密码  7三方登陆  8绑定银行卡
    //    syb.unohacha.com/Api/Api/User_getMessage
    private void registerCode() {
        Map<String,String> map = new HashMap<>();
        map.put("code", Url.CODE);
        map.put("mobile", Base64Util.encodedString2(phone));
//        map.put("mobile", phone);
        map.put("type", "1");
        Log.e("获取验证码", "" + Url.REGISTER_GETCODE);
        OkGo.<InfoBean>post(Url.REGISTER_GETCODE)
                .tag(this)
                .params(map,false)
                .execute(new DialogCallback<InfoBean>(this) {
                    @Override
                    public void onSuccess(Response<InfoBean> response) {
                        Log.e("REGISTER_GETCODE", "" + response.body());
                        if (response.body().getRe().equals("1")) {
                            handler.sendEmptyMessage(100);
                            MyToast(response.body().getInfo());
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                    @Override
                    public void onError(Response<InfoBean> response) {
                        super.onError(response);
                    }
                });
    }


    @Override
    protected void handleMsg(Message msg) {
        switch (msg.what) {
            case 100:
                CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(tv_register_getcode, 60000, 1000);
                mCountDownTimerUtils.start();
                break;
            case 101:
                SharedPreferences sp = getSharedPreferences("userinfo", 0);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("username", phone);
                editor.putString("password", pwd);
                editor.commit();

                Prefer.getInstance().setPhone(phone);
                Prefer.getInstance().setPwd(pwd);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(null!=countDownTimer)
        {
            countDownTimer.onFinish();
            countDownTimer.cancel();
        }
    }
}
